from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.ser import *


# Create your views here.


class TeacherM(APIView):
    def post(self, request):
        ser = TeacherSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'list': '注册成功'})
        else:
            print(ser.errors)
            return Response({'code': 10020, 'list': '用户名重复'})


class TeacherLogin(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if username and password:
            teacher = Teacher.objects.filter(username=username, password=password).first()
            if teacher:
                return Response({'code': '200', 'tid': teacher.id, 'tname': teacher.username})
            else:
                return Response({'code': 10021, 'lost': '登录失败'})


class StuM(APIView):
    def post(self, request):
        ser = StuSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            return Response({'code': 20010})

    def get(self, request):
        tid = request.GET.get('id')
        if tid:
            stu = Stu.objects.filter(teacher_id=tid).all()
        else:
            stu = Stu.objects.filter(teacher_id__isnull=True).all()
        ser = StuSer(stu, many=True)
        return Response({'code': 200, 'list': ser.data})

    def put(self, request):
        id = request.GET.get('id')
        tid = request.GET.get('tid')
        if tid:
            Stu.objects.filter(id=id).update(teacher_id=tid)
        else:
            Stu.objects.filter(id=id).update(teacher_id='')
        return Response({'code': 200})
